package com.fanghuyun.iswaf.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.fanghuyun.iswaf.function.Upload;


public class ClientLogger {
	
	private static Logger logger = Logger.getLogger("iswaf");
	
	public static String getAttackHash(HttpServletRequest request){
		Enumeration<?> e = request.getParameterNames();
		StringBuilder sb = new StringBuilder();
		while (e.hasMoreElements()) {
			sb.append(e.nextElement());
		}
		return DigestUtils.md5Hex(request.getRemoteAddr()+request.getRequestURI()+sb);
	}
	
	public static void addAttackLogs(HttpServletRequest request,String logType){
		try {
			SysConfig sysConfig = new SysConfig();
			Map<String,Object> map = new HashMap<String, Object>();
			File logDirectory = new File(sysConfig.getDatabaseDirectory());
			if(!logDirectory.exists()){
				logDirectory.mkdirs();
			}
			String file = sysConfig.getDatabaseDirectory()+getAttackHash(request);
			if(!new File(file).exists()){
				map.put("hash", getAttackHash(request));
				map.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				map.put("date_default_timezone_get", TimeZone.getDefault());
				map.put("domain", request.getServerName());
				map.put("remoteip", request.getRemoteAddr());
				map.put("serverip", request.getLocalAddr());
				map.put("path", request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\", "/"));
				map.put("hash", getAttackHash(request));
				map.put("get", request.getQueryString());
				map.put("post", sysConfig.getRequestParameter(request));
				map.put("file", Upload.getFormData(request));
				map.put("hash", getAttackHash(request));
				map.put("hash", getAttackHash(request));
				map.put("hash", getAttackHash(request));
				map.put("hash", getAttackHash(request));
				
				BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
				bw.write(
					new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" "+
					request.getServerName()+" "+request.getRemoteAddr()+" "+logType+" \""+
					request.getMethod()+"\" "+request.getRequestURI()+" "+
					sysConfig.getRequestParameterAndCookie(request)+" "+
					sysConfig.getRequestHeaders(request)+ "\n"+
					"[attack:1]"
				);
				bw.flush();
				bw.close();
			}else{
				String fileContent = FileUtils.readFileToString(new File(file));
				String count = fileContent.indexOf("[attack:")!=-1?fileContent.substring(fileContent.lastIndexOf("[attack:")+8,fileContent.lastIndexOf("]")):"";
				FileUtils.writeStringToFile(new File(file), fileContent.replace("[attack:"+count+"]", "[attack:"+(Integer.parseInt(count)+1)+"]"));
			}
		} catch (IOException e) {
			logger.error(e);
		}
		
	}

}
